package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //提交订单  首先判断  地址是否填写
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //地址为空不能下单
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //明确一个用户一个购物车  根据用户id 获取购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //获取购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(shoppingCart);
        //然后判断购物车是否为空
        if (cartList == null || cartList.size() == 0) {
            //购物车为空  不能下单
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //创建订单表
        Orders orders = new Orders();
        //拷贝数据
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());//用户id
        orders.setAddress(addressBook.getDetail());  //地址信息
        orders.setPhone(addressBook.getPhone()); //手机号码
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setNumber(String.valueOf(System.currentTimeMillis())); //订单号  使用时间戳 转字符串
        orders.setStatus(Orders.PENDING_PAYMENT);//状态  待付款
        orders.setPayStatus(Orders.UN_PAID); //支付状态  //未支付
        orders.setOrderTime(LocalDateTime.now());//下单时间

        //提交订单  订单表添加一条数据
        orderMapper.insert(orders);

        //详情表是多条数据  我们new一个集合
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //将购物车的数据遍历出来
        for (ShoppingCart cart : cartList) {
            //创建订单详情表
            OrderDetail orderDetail = new OrderDetail();
            //将购物车数据拷贝到详情表中
            BeanUtils.copyProperties(cart, orderDetail);
            //设置详情表对应的订单表
            orderDetail.setOrderId(orders.getId());
            //将一个个详情表添加到详情表集合中
            orderDetailList.add(orderDetail);
        }
        //订单详情表多条数据
        orderDetailMapper.insertBatch(orderDetailList);


        //付款后  清空购物车

            shoppingCartMapper.clear(shoppingCart);


        //返回前端数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //订单支付成功后通知商家端
        HashMap map = new HashMap<>();
        map.put("type", 1); //1 来单提醒  2 客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单:" + outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开启分页插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //查询所有订单数据
        Page<Orders> orders = orderMapper.queryHistoryOrders(ordersPageQueryDTO);
        //创建一个集合用来传给前端
        List<OrderVO> orderVOS = new ArrayList<>();
        //遍历订单信息数据
        for (Orders order : orders) {
            //创建ordervo 将订单信息和订单详情请数据传给前端
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            //根据订单id查询订单详情数据  一个订单可能对应多个订单详情数据
            List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailByOrderId(order.getId());
            //将订单详情数据设置到vo中
            orderVO.setOrderDetailList(orderDetails);
            //将数据加入vo中
            orderVOS.add(orderVO);
        }
        return new PageResult(orders.getTotal(), orderVOS);
    }

    /**
     * 查询订单详情数据
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetailById(Long id) {
        //根据id查询订单数据
        Orders orders = orderMapper.selectOrderById(id);
        //根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailByOrderId(orders.getId());
        //创建订单vo
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    public void cancel(Long id) {

        //根据id获取订单数据
        Orders orders = orderMapper.selectOrderById(id);
        //判断订单是否存在
        if (orders == null) {
            //不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单除了待付款和待接单 可以取消订单  其他情况需要和商家沟通
        if (orders.getStatus() <= 2) {
            //可以直接取消订单
            //修改订单状态
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            //修改
            orderMapper.update(orders);
        } else {
            //需要沟通

            //退款
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setCancelReason("客户退单");
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);

        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @Override
    public void repetitionOrder(Long id) {
        //根据id查询订单信息
        Orders orders = orderMapper.selectOrderById(id);

        //根据订单id查询订单详情数据
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailByOrderId(id);
        //创建购物车集合
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        //遍历订单详情数据
        for (OrderDetail orderDetail : orderDetails) {
            //创建购物车
            ShoppingCart shoppingCart = new ShoppingCart();
            //将订单详情数据放入购物车中
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            //明确一个用户对应一个购物车   将数据放入购物车
            shoppingCart.setUserId(orders.getUserId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCarts.add(shoppingCart);
        }
        //将购物车批量添加到购物车集合中
        shoppingCartMapper.insertBatch(shoppingCarts);
    }


    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //根据订单的状态来查询
        //待接单
        Integer tobeconfirmed = orderMapper.statistics(Orders.TO_BE_CONFIRMED);
        //待配送
        Integer confirmed = orderMapper.statistics(Orders.CONFIRMED);
        //配送中
        Integer deliveryinprogess = orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);

        //创建vo对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(tobeconfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryinprogess);
        //返回给前端
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     * @return
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //根据id查询订单信息
        Orders orders = orderMapper.selectOrderById(ordersConfirmDTO.getId());
        //修改订单的状态
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //根据id查询订单信息
        Orders orders = orderMapper.selectOrderById(ordersRejectionDTO.getId());
        //修改订单的状态
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setPayStatus(Orders.REFUND);
        orderMapper.update(orders);
    }

    /**
     * 派送中
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //根据id获取订单信息
        Orders orders = orderMapper.selectOrderById(id);
        //修改状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        //修改开始配送时间
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     * @return
     */
    @Override
    public void complete(Long id) {
        //根据id获取订单信息
        Orders orders = orderMapper.selectOrderById(id);
        //修改状态
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 催单
     * @param id
     * @return
     */
    @Override
    public void reminderOrder(Long id) {
        //根据id查询订单信息
        Orders orders = orderMapper.selectOrderById(id);
        //判断订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        HashMap hashMap = new HashMap();
        hashMap.put("type", 2); //来单提醒
        hashMap.put("orderId", orders.getId());
        hashMap.put("content", "用户催单，订单号：" + orders.getNumber());
        String jsonString = JSON.toJSONString(hashMap);
        webSocketServer.sendToAllClient(jsonString);
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress); //商铺的地址
        map.put("output","json"); //返回json格式
        map.put("ak",ak); //appkey 百度平台中复制

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围"+(distance/1000)+"km");
        }
    }

}
